﻿namespace IBTrader.Indicator.CandleStick
{
    using IBTrader.Charts;
    using System;
    using System.Linq;

    /// <summary>
    /// The Money Flow Index (MFI) is an oscillator that uses both price and volume to measure buying and selling pressure. 
    /// MFI is also known as volume-weighted RSI. 
    /// A ratio of positive and negative money flow is then plugged into an RSI formula to create an oscillator that moves between zero and one hundred. 
    /// As a momentum oscillator tied to volume, the Money Flow Index (MFI) is best suited to identify reversals and price extremes with a variety of signals.
    /// </summary>
    class MFI : BaseVolume
    {
        private double last = 0;
        private int up = 0;
        internal MFI(Worker worker, int interval = 60, int pinterval = 12) : base(worker, 1, interval, pinterval) { }
        protected override void Add(object _, Item item)
        {
            var typical = item.Typical;
            var raw = typical * item.Volume;

            if (last == 0) last = typical;
            if (typical > last) up = 1;
            if (typical < last) up = -1;
            Prices.Add(raw * up);
            var pos = Prices.GetEnumerator().Where(p => p > 0).Sum();
            var neg = Prices.GetEnumerator().Where(p => p < 0).Sum();
            var ratio = Math.Abs(NaN(pos / neg));
            var idx = 100 - 100 / (1 + ratio);
            if (Prices.Init)
                OnHit(item.CloseLine, idx);

            last = typical;
        }
    }
}